clear
clear matrix
clear mata
est drop _all
macro drop _all
set more off


********************************
* SETUP
********************************

*-> 1.	specify folder
cd //put the path to your folder here

*-> 2.	create sub-folder "Data" and store in it: SoJcases.dta, SoJhearings.dta, SoJfirmparties.dta, SoJfirmsurvey.dta, SoJjudges.dta

cap mkdir "Tables"
cap mkdir "Figures"

*-> 3. user-written commands used in this do-file; choose 1 to install
global install_packages 0
if $install_packages == 1 {
	ssc install estpost, replace
	ssc install lincomest, replace 
	ssc install coefplot, replace
	ssc install parmest, replace
	ssc install ietoolkit, replace
	ssc install balancetable, replace
}

*-> 3. to replicate figureA5 (created in R) from within Stata 
global r_insall 0 //choose 1 to install relevant R packages
global Rexe C:\Program Files\R\R-4.0.5\bin\R.exe //change to your path to R.exe


*-> 4. layout options
local stars=1 //choose 1 for tables with stars, 0 for tables without
if `stars'==1{
	global star star 
	global starlevels Significance levels are denoted as follows: `"* p$<$0.10, ** p$<$0.05, *** p$<$0.01."'
}
set printcolor gs1 //set for figures in black and white

*-> 5. other
/*	NOTE:	reference chamber for event-studies: code_chambre==44
			reference period for case-level event-studies in aligned time: tentafterT==996
			reference period for case-level event-studies in real time: tentry=77
			reference period for hearing-level event-studies: tsinceTa=996
			tsinceTa=996 as  (ib996) for hearing-level models, 
*/
* macro to exclude adjustment period from analysis
global withoutadj tentafterT<-3 | tentafterT>2

*-> 5. run this do-file; it will create figures and tables in the respective subfolders


/*
************************************************************************************************
************************************************************************************************
* S U M M A R Y

* 0. DEFINE PROGRAMS
* 1. DEFINE TABLE NOTES
* 2. DURATION MODEL FIGURES AND TABLE INPUT
* 3. TABLE INPUT
* 4. TABLES
* 5. FIGURES
* 6. REMOVE TEMP FILES

************************************************************************************************
************************************************************************************************
*/
 

********************************
* 0. DEFINE PROGRAMS
********************************

* main graphs program
********************************
cap program drop mygraphP 
program define mygraphP
syntax anything, [Recode(string) Ifcond(string) Save(string) Options(string) Noconfid(string) xl(string)]
preserve
	parmest, norestore level(95)
	keep if regexm(parm,"`anything'")
	split parm, parse(".") gen(x)
	replace x1=subinstr(x1,"b","",.)
	replace x1=subinstr(x1,"o","",.)
	destring x1, replace
	if `recode'==1{
		replace x1=x1-1000 /*reconverting regressors that are recoded before running the models because they can take negative values*/
	}
	drop x2
	rename x1 `anything'
	if "`anything'"=="tentry"{
		local v=43
		forval i=0/73{
			label define tlab `v' "`i'", modify
			local v=`v'+1
		}
		label val tentry tlab
	}

	local xtitle "xtitle("")"
	cap if "`noconfid'"!="1"{
		local showconfid (line min95 `anything', lcolor(gs14) lpattern(solid)) (line max95 `anything', lcolor(gs14) lpattern(solid))
	}
	if "`xl'"=="1"{
		local xline xline(-3.5, lcolor(black)) xline(2.5, lcolor(black)) 
	}
	if "`xl'"=="2"{
		local xline xline(81, lcolor(black))  
	}
	*option to display all cutoffs in same graph for placebo graphs -- first cutoff in dash 
	if "`xl'"=="3"{
		local xline xline(81, lcolor(red) lpattern(dash)) xline(84, lcolor(black)) xline(87, lcolor(black)) xline(88, lcolor(black)) xline(89, lcolor(black)) 
	}
	*option to display all cutoffs in same graph for placebo graphs -- first two cutoffs out  
	if "`xl'"=="4"{
		local xline xline(81, lcolor(red) lpattern(dash)) xline(84, lcolor(red) lpattern(dash)) xline(87, lcolor(black)) xline(88, lcolor(black)) xline(89, lcolor(black)) 
	}
	if "`xl'"=="5"{
		local xline xline(81, lcolor(red) lpattern(dash)) xline(84, lcolor(red) lpattern(dash)) xline(87, lcolor(red) lpattern(dash)) xline(88, lcolor(black)) xline(89, lcolor(black)) 
	}
	if "`xl'"=="6"{
		local xline xline(81, lcolor(red) lpattern(dash)) xline(84, lcolor(red) lpattern(dash)) xline(87, lcolor(red) lpattern(dash)) xline(88, lcolor(red) lpattern(dash)) xline(89, lcolor(black)) 
	}
	twoway (connected estimate `anything') `showconfid' `ifcond', `xtitle' `options' ytitle("") `xline' scheme(s2mono) legend(off)
	graph save "Figures\Graph_`anything'_`save'", replace
restore
end program


* interacted graphs program
********************************
cap program drop mygraphP2
program define mygraphP2
syntax anything, [Recode(string) If(string) Save(string) Options(string) Lab1(string) Lab0(string) Type1(string)]
preserve

	parmest, norestore level(90 95)
	keep if regexm(parm,"`anything'")

	gen type1=regexm(parm,"`type1'")
	split parm, parse("`anything'") gen(x)
	destring x2, replace
	drop x1	
	if `recode'==1{
		replace x2=x2-1000 /*reconverting regressors that are recoded before running the models because they can 
							 take negative values*/
	}
	rename x2 `anything'

	label var min90 ""
	label var max90 ""
	label var min95 ""
	label var max95 ""
	gen estimate0=estimate
	rename estimate estimate1
	label var estimate0 `lab0'
	label var estimate1 `lab1'
	
	keep estimate? min9? max9? type? `anything'
	*create the -1 comparison at 0
	bysort type1 (`anything'): gen n=_n
	gen b=1
	replace b=2 if n==1
	expand b, gen(new)
	forval v=0/1{
		replace estimate`v'=0 if new==1
	}
	replace min90=0 if new==1
	replace max90=0 if new==1
	replace min95=0 if new==1
	replace max95=0 if new==1
	replace `anything'=-1 if new==1
	sort type1 `anything'
	
	if "`anything'"=="tentafterT"{
		local xtitle "xtitle("t between entry and T")"
	}
	twoway (connected estimate1 `anything' if type1==1) ///
		(line min95 `anything' if type1==1, lcolor(gs14) lpattern(solid)) ///
		(line max95 `anything' if type1==1, lcolor(gs14) lpattern(solid)) ///
		(connected estimate0 `anything' if type1==0, color(midgreen) lpattern(dash)) ///
		(line min95 `anything' if type1==0, lcolor(olive_teal) lpattern(dash)) ///
		(line max95 `anything' if type1==0, lcolor(olive_teal) lpattern(dash)) ///
		`if', `xtitle' `options' legend(order(1 4) ring(0) pos(2) col(1)) scheme(s2mono)
	graph save "Figures\Graph_`anything'_`save'", replace
restore
end program


* main tables program
********************************
cap program drop tabprep
program define tabprep
syntax , [Name(string) Contrcond(string) Addlocal(string)]
	est store `e(depvar)'_`name'
	estadd scalar bootp=r(p)
	qui sum `e(depvar)' `contrcond'
	estadd scalar premean=r(mean)
	estadd scalar presd=r(sd)
	estadd local FE1 Yes
	estadd local FE2 Yes
	estadd local `addlocal'
end program


* interacted tables program
********************************
cap program drop itabprep
program define itabprep
syntax , [Name(string) Contrcond(string) Addlocal(string) Linvar(string) Fe1(string) FE3(string)]
	est store `e(depvar)'_`name'
	estadd scalar bootp=r(p)
	qui sum `e(depvar)' `contrcond' 
	estadd scalar premean=r(mean)
	estadd scalar presd=r(sd)
	estadd local FE1 `fe1'		
	estadd local FE2 Yes
	estadd local FE3 `fe3'
	estadd local `addlocal'
	preserve 
		lincomest (1.entafterT+1.`linvar'#1.entafterT)
		parmest, norestore
		format p estimate stderr %5.2f
		levelsof p if(_n==1), local(p)
		levelsof estimate if(_n==1), local(estimate)
		levelsof stderr if(_n==1), local(stderr)
	restore
	est resto `e(depvar)'_`name'
	estadd scalar pval=round(`p',.01)
	estadd scalar coef=round(`estimate',.01)
	estadd scalar se=round(`stderr',.01)
	boottest 1.entafterT+1.`linvar'#1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	estadd scalar bootp2=r(p)
end program



********************************
* 1. DEFINE TABLE NOTES
********************************

* main tables
********************************

local tablenotes2 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on pre-trial proceedings. Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree. All models include chamber-specific linear trends allowed to change after the decree (full interaction of chamber FEs, trend, and Entered after decree application), calendar month fixed effects and a constant. All models estimated by OLS. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. 4795 observations, except for col 1 (censoring), col 7 (only for cases that have more than one hearing), col 8 (only for cases that have any adjournments). $starlevels \end{tablenotes}

local tablenotes3 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on pre-trial proceedings. Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree; above median claim is a dummy that takes value 1 when a case's claim amount is above the median claim amount recorded over the study period. All models include chamber-specific linear trends allowed to change after the decree (full interaction of chamber FEs, trend, and Entered after decree application), calendar month fixed effects, and a constant. All models estimated by OLS. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. Difference in number of observations compared to Table 2 due to missing claim amounts. $starlevels \end{tablenotes}   
                         
local tablenotes4 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on pre-trial proceedings. Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree; fast judge is a dummy that takes value 1 when a judge's baseline pre-trial speed is above the median baseline pre-trial speed. All models include a linear trend - allowed to change after the decree (Interaction), calendar month fixed effects, amount category dummies, a collegiate pre-trial dummy, and a constant. All models estimated by OLS. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. Difference in number of observations compared to Table 2 due to missing baseline speed of case judge. $starlevels \end{tablenotes}

local tablenotes5 \begin{tablenotes} \item[] \underline{Notes}: Model 1 is the base specification. In Model 2 the pre-trial speed variable is the fast pre-trial dummy, in Model 3 it is pre-trial duration (in 100 days). In cols 1-3, 5-7 the dependant variable is monthly log revenues; col 4 is the first stage for the IV of col 3, and col 8 is the first stage for the IV of col 7; col 5 is the reduced form. After case started is a dummy that takes value 1 for a case parties' observations after its pre-trial has started, and value 0 before pre-trial start and for firms in the sample that do not have a court case in the study period. Fast pre-trial is a dummy that takes value 1 when a case party's pre-trial was completed in four months or less; Pre-trial duration is its duration (in 100 days). After decree is a dummy that takes value 1 when a party's case started its pre-trial after the application of the decree. All models include case party and month fixed effects and are estimated by OLS; cols 1-5 include 12 observations for each of the 1622 case parties (6 months before pre-trial start and 6 months after) as well as uninterrupted spells of log revenue observations of at least 12 months (average: 33.046 months) within the study period for 8,575 firms that did not have a court case; the same holds for cols 6-8 but with only 1520 case parties due to the censoring of the pre-trial duration variable. Standard errors in parentheses, clustered at the firm-level. $starlevels Pre-mean and pre-sd refer to sample average and standard deviation respectively of case parties' log revenues in the month before pre-trial start. \end{tablenotes}


*appendix tables
********************************

local tablenotesA1 \begin{tablenotes} \item[] \underline{Notes}: The table shows yearly descriptive statistics at the chamber level over the 2012/15 period. The first panel reports the average incoming number of cases per hearing. The second panel reports the average number of cases undergoing pre-trial stage per hearing. The third panel reports the average number of cases undergoing decision stage per hearing. \end{tablenotes}

local tablenotesA2 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on pre-trial proceedings. Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree. All models include a linear trend - allowed to change after the decree (Interaction)-, chamber and calendar month fixed effects, and a constant. All models estimated by OLS. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. 5297 observations, except for col 1 (censoring), col 7 (only for cases that have more than one hearing), col 8 (only for cases that have any adjournments). \end{tablenotes} 

local tablenotesA3 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on pre-trial proceedings. Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree. All models include a linear trend - allowed to change after the decree (Interaction)-, chamber and calendar month fixed effects, and a constant. All models estimated by OLS. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. 4795 observations, except for col 1 (censoring), col 7 (only for cases that have more than one hearing), col 8 (only for cases that have any adjournments). $starlevels \end{tablenotes}

local tablenotesA4 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on pre-trial proceedings. Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree; above median claim is a dummy that takes value 1 when a case's claim amount is above the median claim amount recorded over the study period. All models include a linear trend - allowed to change after the decree (Interaction), chamber and calendar month fixed effects, and a constant. All models estimated by OLS. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. Difference in number of observations compared to Table 2 due to missing claim amounts. $starlevels \end{tablenotes}                            
local tablenotesA5 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on pre-trial proceedings. Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree; fast judge is a dummy that takes value 1 when a judge's baseline pre-trial speed is above the median baseline pre-trial speed. All models include chamber-specific linear trends allowed to change after the decree (full interaction of chamber FEs, trend, and Entered after decree application), calendar month fixed effects, amount category dummies, a collegiate pre-trial dummy, and a constant. All models estimated by OLS. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. Difference in number of observations compared to Table 2 due to missing baseline speed of case judge. $starlevels \end{tablenotes}

local tablenotesA6 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on decision-stage proceedings. See Notes on Table 2. 3844 observations for decision stage outcomes, except col 1 (censoring). \end{tablenotes}

local tablenotesA7 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on the quality of pre-trial and deliberation proceedings. See Notes on Table 2. 3844 observations for decisoin stage outcomes, except cols 1-2 (censoring as only for cases with at least one decision stage hearing), and cols 3-5 (missing outcomes). \end{tablenotes}

local tablenotesA8 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on decision-stage proceedings. See Notes for cols 2-4, Table A4. 4214 observations for decision stage outcomes, except col 1 (censoring). \end{tablenotes} 

local tablenotesA9 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on decision-stage proceedings. See Notes on Table A4. 3844 observations for decision stage outcomes, except col 1 (censoring). \end{tablenotes}

local tablenotesA10 \begin{tablenotes} \item[] \underline{Notes}: Estimates of case-level impacts of the reform on the quality of pre-trial and deliberation proceedings. See Notes on Table A4. 3844 observations for decisoin stage outcomes, except cols 1-2 (censoring as only for cases with at least one decision stage hearing), and cols 3-5 (missing outcomes). \end{tablenotes}

local tablenotesA11 \begin{tablenotes} \item[] \underline{Notes}: In panels A and B all questions after the first refer to the most recent case. Total amount spent includes lawyer fees, court fees, and informal payments. Respondants who indicated positive numbers of hours lost without giving a number said it was impossible to quantify but large. \end{tablenotes} 

local tablenotesA12 \begin{tablenotes} \item[] \underline{Notes}: Models 1 and 2 of Table 8 restricted to the sample with non-missing pre-trial duration (as for Model 3 of Table 8). The dependant variable in cols 1-4 is monthly log revenues; col 4 is the first stage for the IV of col 3; col 5 is the reduced form. After case started is a dummy that takes value 1 for a case parties' observations after its pre-trial has started, and value 0 before pre-trial start and for firms in the sample that do not have a court case in the study period. Fast pre-trial is a dummy that takes value 1 when a case party's pre-trial was completed in four months or less. After decree is a dummy that takes value 1 when a party's case started its pre-trial after the application of the decree. All models include case party and month fixed effects and are estimated by OLS; they include 12 observations for each of the 1520 case parties with non-missing pre-trial duration (6 months before pre-trial start and 6 months after) as well as uninterrupted spells of log revenue observations of at least 12 months (average: 33.046 months) within the study period for 8,575 firms that did not have a court case. Standard errors in parentheses, clustered at the firm-level. $starlevels Pre-mean and pre-sd refer to sample average and standard deviation respectively of case parties' log revenues in the month before pre-trial start. \end{tablenotes}

local tablenotesA13 \begin{tablenotes} \item[] \underline{Notes}: Ancova versions of Models 2 and 3 of Table 8. In Model 2 the pre-trial speed variable is the fast pre-trial dummy, in Model 3 it is pre-trial duration (in 100 days). In cols 1-2, 4-6 the dependent variable is average monthly log revenues after the start of the pre-trial; col 3 is the first stage for the IV of col 2; col 7 is the first stage for the IV of col 6; col 4 is the reduced form. Fast pre-trial is a dummy that takes value 1 when a case party's pre-trial was completed in four months or less; Pre-trial duration (in 100 days) is its duration. After decree is a dummy that takes value 1 when a party's case started its pre-trial after the application of the decree. All models include chamber and calendar month fixed effects, control for six baseline values of log monthly revenues (the six months before the start of the pre-trial), and include a constant. All models are estimated by OLS; for cols 1-4 they include one observations for each of the 1622 case parties; for cols 5-7 this number is 1520 due to the censoring of the pre-trial duration variable. Standard errors in parentheses, clustered at the (chamber x hearing of entry) level. $starlevels Pre-mean and pre-sd refer to sample average and standard deviation respectively of case parties' log revenues in the month before pre-trial start. \end{tablenotes}

local tablenotesA14 \begin{tablenotes} \item[] \underline{Notes}: Estimates of firm-level impacts of the reform on perceived duration and costs, hypothetical use, and perception of the justice system. Uneven cols: sample is all firms, Case(s) after decree applic. is a dummy that takes value one if a firm has had at least one case after decree application. controls include the number of cases the firm had. Even cols: sample restricted to firms that had only one case, Case after decree applic. is a dummy that indicates the case was after the introduction of the decree. All models control for baseline number of employees, include a constant, and are estimated by OLS. $starlevels \end{tablenotes}  

local tablenotesA16 \begin{tablenotes} \item[] \underline{Notes}: Balance on decree effect size. Panel A: Comparing decree effect size for case parties across court-only and tax record sample; as in the tax record analysis using ANCOVA, controls include chamber fixed effects and calendar month fixed effects, and standard errors (in parentheses) are clustered at the (chamber x hearing of entry) level. Panel B: Comparing decree effect size for firms across court-only and firm survey sample; as in the firm survey analysis, we control for the number of cases the firm had; as the baseline number of employees (also controlled for in that analysis) stems from the firm survey, here we use baseline (2012) revenues (inverse hyperbolic sine transformation) to control for firm size instead; robust standard errors in parentheses. All models estimated by OLS. $starlevels \end{tablenotes}

local tablenotesA17 \begin{tablenotes} \item[] \underline{Notes}: Structural break diagnostic at the chamber-hearing (col 1) and case (cols 2-4) levels. Col 1: Hearing after decree application is a dummy that takes value 1 if the hearing is taking place after the chamber's application of the decree. Cols 2-6: Entered after decree application is a dummy that takes value 1 when a case entered its assigned chamber after the application of the decree. Cols 1-6: All models include a linear trend - allowed to change after the decree (Interaction), chamber and calendar month fixed effects, and a constant. Col 1: standard errors clustered at the hearing level. Cols 2-6: standard errors are clustered at the (chamber x hearing of entry) level. Window includes cases entering between 38 and 4 hearings before and between 4 and 21 hearings after decree application. $starlevels \end{tablenotes}



********************************
* 2. DURATION MODEL FIGURES AND TABLE INPUT
********************************

* FIGURE 2, PANELS B&D (DURATION MODEL FOR PRE-TRIAL DURATION)
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

gen texit=tfinishmee
replace texit=117 if tfinishmee==. /*non-censored obs are under observation until tfinishmee; censored obs
are under observation until the last t in the dataset, t==117*/
gen finmee=(date_finishmee!=.)
gen tentrym1=tentry-1
stset texit, failure(finmee) origin(time tentrym1) 
label var _t "Hazard ratio - finishing pre-trial"


sts graph, by(entafterT) xtitle(t) xlabel(0(10)60) title("") legend(title(Time of entry, size(medsmall) position(11)) position(2) ring(0) rows(2) order(1 "Before" 2 "After")) title(D. Kaplan-Meier survival estimates, size(medium))scheme(s2mono) 
graph save "Figures\figure2D.gph", replace

replace tentafterT=tentafterT+1000 
stcox ib996.tentafterT ib1.entcalmth ib44.code_chambre2, vce(cluster cham2_tentry)
mygraphP tentafterT, save(durmodmee) options("xlabel(-40(8)20) xtitle(chamber entry period) title(B. Hazard ratio (exiting pre-trial), size(medium))") xl(1) recode(1)
replace tentafterT=tentafterT-1000 


* INPUT FOR TABLE 2, COL 2; TABLE A2, COL 2, TABLE A3, COL 2 (DURATION MODEL FOR PRE-TRIAL DURATION)
********************************

local outcome durmod

stcox i.entafterT tentafterT i.entafterT#c.tentafterT ib44.code_chambre2#c.tentafterT i.entafterT#ib44.code_chambre2#c.tentafterT ib44.code_chambre2 ib1.entcalmth if $withoutadj, vce(cluster cham2_tentry)
est store `outcome'_F
estadd local FE1 Yes
estadd local FE2 Yes
estadd local woadj Yes

stcox i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2, vce(cluster cham2_tentry)
est store `outcome'_B
estadd local FE1 Yes
estadd local FE2 Yes
estadd local woadj No

stcox i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2 if $withoutadj, vce(cluster cham2_tentry)
est store `outcome'_A
estadd local FE1 Yes
estadd local FE2 Yes
estadd local woadj Yes


* FIGURE 4, PANEL F (DURATION MODEL FOR CASE DURATION)
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

gen tjexit=tjugement
replace tjexit=117 if tjugement==. /*non-censored obs are under observation until tjugement; censored obs
are under observation until the last t in the dataset, t==117*/
gen fin=(date_jugement!=.)

gen tentrym1=tentry-1
stset tjexit, failure(fin) origin(time tentrym1) 
label var _t "Hazard ratio - finishing case"

sts graph, by(entafterT) xtitle(t) title("") legend(title(Time of entry, size(medsmall) position(11)) position(2) ring(0) rows(2) order(1 "Before" 2 "After")) title(F. Kaplan-Meier survival estimates - full case, size(medium))scheme(s2mono) 
graph save "Figures\figure4F.gph", replace


* FIGURE 4, PANEL B (DURATION MODEL FOR DECISION DURATION)
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

keep if numaudaftermee!=. //only for those that have a decision stage

gen tjexit=tjugement
replace tjexit=117 if tjugement==. /*non-censored obs are under observation until tjugement; censored obs
are under observation until the last t in the dataset, t==117*/
gen fin=(date_jugement!=.)
stset tjexit, failure(fin) origin(time tfinishmee) 
label var _t "Hazard ratio - finishing decision stage"

replace tentafterT=tentafterT+1000 
stcox ib996.tentafterT ib1.entcalmth ib44.code_chambre2, vce(cluster cham2_tentry)
mygraphP tentafterT, save(durmoddec) options("xlabel(-40(8)20) xtitle(chamber entry period) title(B. Hazard ratio (exiting decision), size(medium))") xl(1) recode(1)
replace tentafterT=tentafterT-1000 


* INPUT FOR TABLE A6, COL 2; TABLE A8, COL 2; TABLE A9, COL 2 (DURATION MODEL FOR DECISION DURATION)
********************************

local outcome durdec

stcox i.entafterT tentafterT i.entafterT#c.tentafterT ib44.code_chambre2#c.tentafterT i.entafterT#ib44.code_chambre2#c.tentafterT ib44.code_chambre2 ib1.entcalmth if $withoutadj, vce(cluster cham2_tentry)
est store `outcome'_F
estadd local FE1 Yes
estadd local FE2 Yes
estadd local woadj Yes

stcox i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2, vce(cluster cham2_tentry)
est store `outcome'_B
estadd local FE1 Yes
estadd local FE2 Yes
estadd local woadj No

stcox i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2 if $withoutadj, vce(cluster cham2_tentry)
est store `outcome'_A
estadd local FE1 Yes
estadd local FE2 Yes
estadd local woadj Yes



********************************
* 3. TABLE INPUT
********************************

* INPUT FOR TABLE 2, COLS 1 & 3-8; TABLE A2, COLS 1 & 3-8; TABLE A3, COLS 1 & 3-8; TABLE A6, COLS 1 & 3-5; TABLE A7; TABLE A8, COLS 1 & 3-5; TABLE A9, COLS 1 & 3-5; TABLE A10
*********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

label var delibwopt "Fast-tracked"
label var article_num "Number of articles"
label var taille_rel "Decision length"
label var dummy_exp "Appeal"

#delimit ; 

local flexmodel i.entafterT tentafterT i.entafterT#c.tentafterT ib44.code_chambre2#c.tentafterT 
	i.entafterT#ib44.code_chambre2#c.tentafterT ib44.code_chambre2 ib1.entcalmth if $withoutadj, cluster(cham2_tentry);

#delimit cr 

foreach outcome in duree_mee meein4 duree_decision decisionin1 deskrej delibwopt numaudmee shheardmee ferme_among_renvoi numaudaftermee shheardaftermee aftermee_hasrab aftermee_haspro article_num taille_rel_surce dummy_exp{
	reg `outcome' `flexmodel'
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	tabprep, name(F) addlocal(woadj Yes) contrcond("if tentafterT<-3")
	reg `outcome' i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2 if $withoutadj, cluster(cham2_tentry)
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	tabprep, name(A) addlocal(woadj Yes) contrcond("if tentafterT<-3")
	reg `outcome' i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2, cluster(cham2_tentry)
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	tabprep, name(B) addlocal(woadj No) contrcond("if tentafterT<0")
}


* INPUT FOR TABLES 3, 4, A5, A6
********************************

use "Data\SoJcases", clear

label var delibwopt "Fast-tracked"

#delimit ;

local flexintmodelC i.montabm##i.entafterT##c.tentafterT ib44.code_chambre2#c.tentafterT 
	i.entafterT#ib44.code_chambre2#c.tentafterT ib44.code_chambre2 ib1.entcalmth if $withoutadj, cluster(cham2_tentry);
local flexintmodelD i.magspeedabm##i.entafterT##c.tentafterT ib44.code_chambre2#c.tentafterT 
	i.entafterT#ib44.code_chambre2#c.tentafterT ib1.entcalmth ib1.mont_quint2 magcolleg3 if $withoutadj, cluster(cham2_tentry);
	
#delimit cr

foreach outcome in duree_mee meein4 deskrej delibwopt numaudmee shheardmee ferme_among_renvoi aftermee_hasrab aftermee_haspro{
	reg `outcome' `flexintmodelC'
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	itabprep, name(FC) linvar(montabm) addlocal(woadj Yes) contrcond("if tentafterT<-3 & montabm==0") fe1(Yes)
	reg `outcome' `flexintmodelD' 
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	itabprep, name(FD) linvar(magspeedabm) addlocal(woadj Yes) contrcond("if tentafterT<-3 & magspeedabm==0") fe1(No) fe3(Yes)
	reg `outcome' i.montabm##i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2 if $withoutadj, cluster(cham2_tentry)
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	itabprep, name(C) linvar(montabm) addlocal(woadj Yes) contrcond("if tentafterT<-3 & montabm==0") fe1(Yes)
	reg `outcome' i.magspeedabm##i.entafterT##c.tentafterT ib1.mont_quint2 magcolleg3 ib1.entcalmth if $withoutadj, cluster(cham2_tentry)
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	itabprep, name(D) linvar(magspeedabm) addlocal(woadj Yes) contrcond("if tentafterT<-3 & magspeedabm==0") fe1(No) fe3(Yes)
}
	

* INPUT FOR TABLE A17
***********************************

use "Data\SoJhearings", clear
drop if tsinceTa<-38 | tsinceTa>20
**time period is restricted to the same window used for main regressions
label var tsinceTa "t since decree application"
label var numin "Number of incoming cases"

reg numin i.audafterTa##c.tsinceTa ib1.calmth ib44.code_chambre if (tsinceTa<-3 | tsinceTa>2), cluster(t)
boottest 1.audafterTa=0 , cluster(code_chambre) weight(webb) reps(20000) seed(10101) nograph
tabprep, name(A) addlocal(woadj Yes) contrcond("if tsinceTa<-3")


use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

label var moredemordef "More parties"
label var montabm "Above median claim"
label var typecommercial "Commercial case"

foreach outcome in montabm moredemordef{
	reg `outcome' i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2 if $withoutadj, cluster(cham2_tentry)
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	tabprep, name(A) addlocal(woadj Yes) contrcond("if tentafterT<-3")
}
reg typecommercial i.entafterT##c.tentafterT ib1.entcalmth if $withoutadj, cluster(cham2_tentry)
boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
tabprep, name(A) addlocal(woadj Yes) contrcond("if tentafterT<-3")

/*commented out as istca2012 cannot be included in the replication data

use "Data\SoJfirmparties", clear

foreach outcome in istca2012{
	forval v=0/2{
		if "`v'"=="0"{
			local if if istca2012!=. //to ensure the below code works also for v=0
		}
		if "`v'"=="1"{
			local if if side1==1
		}
		if "`v'"=="2"{
			local if if side2==1
		}
	reg `outcome' i.entafterT##c.tentafterT ib1.entcalmth ib44.code_chambre2 `if' & ($withoutadj), cluster(cham2_tentry)
	boottest 1.entafterT=0 , cluster(code_chambre2) weight(webb) reps(20000) seed(10101) nograph
	tabprep, name(A`v') addlocal(woadj Yes) contrcond("`if' & tentafterT<-3")
	}
}
*/
	
	

********************************
* 4. TABLES
********************************

* TABLE 1 (SUMMARY STATS)
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

estpost tabstat duree_mee meein4 duree_decision decisionin1 finjug fincon finradandoth delibwopt ferme_among_renvoi numaudmee numaudaftermee shheardmee shheardaftermee aftermee_hasrab aftermee_haspro moredemordef if tentafterT<-3, columns(statistics) stat(n mean sd med min max)
*montant1, numdem, numdemfirm, numdempriv, numdef, numdeffirm, numdefpriv, removed here for anonymization
#delimit;
	estout using "Tables\table1.tex", replace
	cells("count mean(fmt(%012.2fc)) sd(fmt(%012.2fc)) p50(fmt(%012.2fc)) min(fmt(%012.2fc)) max(fmt(%012.2fc))") delim("&") style(tex) 
	modelwidth(14) collabels(N Mean StD Median Min Max) mlabels(,none) label wrap
	refcat(duree_mee "PANEL A: Case-level characteristics and outcomes", nolabel)
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{7}{>{\centering\arraybackslash}p{1.4cm}}} \hline \hline) 
	posthead(\hline)
;
#delimit cr


/*Panel B of Table 1 commented out as t_ca2012 and istca2012 cannot be included in the replication data

use "Data\SoJfirmparties", clear

replace t_ca2012=t_ca2012/1000000000
label var t_ca2012 "2012 revenues (in billion FCFA)"
estpost tabstat t_ca2012 istca2012 if tentafterT<-3, columns(statistics) stat(n mean sd med min max)

#delimit;
	estout using "Tables\table1.tex", append
	cells("count mean(fmt(%012.2fc)) sd(fmt(%012.2fc)) p50(fmt(%012.2fc)) min(fmt(%012.2fc)) max(fmt(%012.2fc))") delim("&") style(tex) 
	modelwidth(14) collabels(,none) mlabels(,none) label wrap
	refcat(t_ca2012 "PANEL B: Party-level characteristics", nolabel)
	posthead(\hline)
	postfoot("\hline \hline \end{tabular} 
		\begin{tablenotes} \item \underline{Notes}: Baseline summary statistics, for cases entering between 38 and 4 hearings 
		before decree application. 2671 baseline observations for pre-trial and overall outcomes, except for rows 1, 5-7
		(censoring), 9 (only for cases that have any adjournments), 12 (only for cases that have more than one hearing). 
		2405 baseline observations for decision stage outcomes, except for row 3 (censoring). 
		Fewer observations for case characteristics 16-22 (not available for all cases).
		IHS transformation: Inverse hyperbolic sine transformation. \end{tablenotes}
	\end{threeparttable}
	")
;
#delimit cr
*/


* TABLES 2, A6, A7:
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

label var delibwopt "Fast-tracked"
label var montabm "Above median claim amount"
label var typecommercial "Commercial case"
label var article_num "Number of articles"
label var taille_rel_surce "Decision length"
label var dummy_exp "Appeal"
gen _t=. //to ensure the duration model colums get labelled


local table_2 duree_mee_F durmod_F meein4_F deskrej_F delibwopt_F numaudmee_F shheardmee_F ferme_among_renvoi_F 
local table_A6 duree_decision_F durdec_F decisionin1_F numaudaftermee_F shheardaftermee_F 
local table_A7 aftermee_hasrab_F aftermee_haspro_F article_num_F taille_rel_surce_F dummy_exp_F

foreach i in 2 A6 A7 {
	local exp
	if "`i'"=="2" {
		local exp "eform(0 1 0 0 0 0 0 0)" /*to show hazard ratios instead of beta coefficients for the duration models*/
		label var _t "Hazard ratio - finishing pre-trial"
	}
	if "`i'"=="A6" {
		local exp "eform(0 1 0 0 0)" /*to show hazard ratios instead of beta coefficients for the duration models*/
		label var _t "Hazard ratio - finishing decision stage"
	}
		#delimit;
		estout `table_`i'' using "Tables\table`i'.tex", replace
		cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
		modelwidth(14) collabels(none) label mlabels(`robustlab',depvars) numbers 
		wrap varlabels(_cons "Constant" 1.entafterT "Entered after decree application ($\beta$)" 1.audafterTa "Hearing after decree application") 
		drop(*0.* *calmth* *tentafterT* *code_chambre* _cons) `exp'
		stats(bootp FE1 FE2 woadj premean presd r2 N, fmt(%5.2f %~3s %~3s %~3s %5.2f %5.2f %5.2f %5.0f) labels("P-value 6pWCBoot" "Chamber FE x Trend" "Calendar month FEs" "Without adj. period" "Pre-mean" "Pre-sd" "R-Squared" "Observations"))
		prehead(
		\centering \begin{threeparttable} 
				\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
		posthead(\hline) prefoot(\hline) 
		postfoot(\hline \hline \end{tabular} 
		`tablenotes`i''
		\end{threeparttable} 
		) 
		;
	#delimit cr
}


* TABLE 3:
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

label var delibwopt "Fast-tracked"
local table_3 duree_mee_FC meein4_FC deskrej_FC delibwopt_FC numaudmee_FC shheardmee_FC ferme_among_renvoi_FC
#delimit;
	estout `table_3' using "Tables\table3.tex", replace
	cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
	modelwidth(14) collabels(none) label mlabels(, depvars) numbers wrap 
	varlabels(_cons "Constant" 1.entafterT "Entered after decree application" 1.montabm "Above median claim" 
		1.montabm#1.entafterT "Above median claim X Entered after decree appl." 1.montabm#c.tentafterT "Above median claim X Trend"
		1.montabm#1.entafterT#c.tentafterT "Triple interaction") 
	drop(*0.* *calmth* *code_chambre* tentafterT 1.entafterT#c.tentafterT _cons)
	stats(bootp coef pval bootp2 FE1 FE2 woadj premean presd r2 N, fmt(%5.2f %5.2f %5.2f %5.2f %~3s %~3s %~3s %5.2f %5.2f %5.2f %5.0f) 
	labels("P-value 6pWCBoot: entered after" "Effect for large cases" "P-value: effect for large cases" "P-value 6pWCBoot: large cases" "Chamber FEs x Trend" "Calendar month FEs" "Without adjustment period" "Pre-mean" "Pre-sd" "R-Squared" "Observations"))
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
	posthead(\hline) prefoot(\hline) 
	postfoot(\hline \hline \end{tabular} 
	`tablenotes3'
			\end{threeparttable} 
			) 
	;
#delimit cr


* TABLE 4:
********************************

local table_4 duree_mee_D meein4_D deskrej_D delibwopt_D numaudmee_D shheardmee_D ferme_among_renvoi_D
#delimit;
	estout `table_4' using "Tables\table4.tex", replace
	cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
	modelwidth(14) collabels(none) label mlabels(, depvars) numbers wrap 
	varlabels(_cons "Constant" 1.entafterT "Entered after decree application" tentafterT "Trend" 
			1.entafterT#c.tentafterT "Entered after decree application X Trend"  
			1.magspeedabm "Fast judge" 1.magspeedabm#1.entafterT "Fast judge X Entered after decree application" 
			1.magspeedabm#c.tentafterT "Fast judge X Trend" 1.magspeedabm#1.entafterT#c.tentafterT "Triple interaction"
			magcolleg3 "Collegial pre-trial")
	drop(*0.* *entcalmth *mont_quint2 _cons)
	stats(bootp coef pval bootp2 FE1 FE2 FE3 woadj premean presd r2 N, fmt(%5.2f %5.2f %5.2f %5.2f %~3s %~3s %~3s %~3s %5.2f %5.2f %5.2f %5.0f) 
	labels("P-value 6pWCBoot: entered after" "Effect for fast judges" "P-value: effect for fast judges" "P-value 6pWCBoot: fast judges" "Chamber FEs" "Calendar month FEs" "Amount category controls" "Without adjustment period" "Comparison mean" "Comparison sd" "R-Squared" "Observations"))
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
	posthead(\hline) prefoot(\hline) 
	postfoot(\hline \hline \end{tabular} 
			`tablenotes4'
			\end{threeparttable} 
			) 
	;
#delimit cr



* TABLES 5 & A12: DIFF-IN-DIFF, TAX DATA (not included in the replication files)
********************************

/*
use "$taxlocation\vatrevenues.dta", clear

xtset partyid yrmth

local fe yr

foreach i in 5 A12{
    
	if "`i'"=="A12"{
		local restr if duree_mee100X!=.
		local andrestr & duree_mee100X!=.
	}
	
	*case-effect
	xtreg yyvatLOG treat `fe'mth? `fe'mth?? `restr', fe cluster(ninea)
	est store case
	estadd local FE1 `e(ivar)'
	estadd local FE2 `fe'mth
	qui sum yyvatLOGM01 if mthafterC==1005 `andrestr' //this is only defined for those who do have a case
	estadd scalar premean=r(mean)
	estadd scalar presd=r(sd)
	*OLS
	xtreg yyvatLOG meein4XXtreat treat `fe'mth? `fe'mth?? `restr', fe cluster(ninea)
	est store OLS
	estadd local FE1 `e(ivar)'
	estadd local FE2 `fe'mth
		preserve 
			lincomest (treat+meein4XXtreat)
			parmest, norestore
			format p estimate stderr %5.2f
			levelsof p if(_n==1), local(p)
			levelsof estimate if(_n==1), local(estimate)
			levelsof stderr if(_n==1), local(stderr)
		restore
		est resto OLS
		estadd scalar pval=round(`p',.01)
		estadd scalar coef=round(`estimate',.01)
	*IV
	xtivreg2 yyvatLOG (meein4XXtreat = entafterTXXtreat) treat `fe'mth? `fe'mth?? `restr', fe rf first cluster(ninea)
	est store IV
	estadd local FE1 `e(ivar)'
	estadd local FE2 `fe'mth
		preserve 
			lincomest (treat+meein4XXtreat)
			parmest, norestore
			format p estimate stderr %5.2f
			levelsof p if(_n==1), local(p)
			levelsof estimate if(_n==1), local(estimate)
			levelsof stderr if(_n==1), local(stderr)
		restore
		est resto IV
		estadd scalar pval=round(`p',.01)
		estadd scalar coef=round(`estimate',.01)
	*FS
	xtreg meein4XXtreat entafterTXXtreat treat `fe'mth? `fe'mth?? `restr', fe cluster(ninea)
	est store FS
	estadd local FE1 `e(ivar)'
	estadd local FE2 `fe'mth
	test entafterTXXtreat
	estadd scalar Fstat `r(F)'
	qui sum meein4 if mthafterC==1005 `andrestr' //this is only defined for those who do have a case
	estadd scalar premean=r(mean)
	estadd scalar presd=r(sd)
	*RF
	xtreg yyvatLOG entafterTXXtreat treat `fe'mth? `fe'mth?? `restr', fe cluster(ninea)
	est store RF
	estadd local FE1 `e(ivar)'
	estadd local FE2 `fe'mth

	if "`i'"=="5"{
		*OLS, continuous
		xtreg yyvatLOG d100XXtreat `fe'mth? `fe'mth?? if duree_mee100X!=., fe cluster(ninea)
		est store OLS2
		estadd local FE1 `e(ivar)'
		estadd local FE2 `fe'mth
		qui sum yyvatLOGM01 if mthafterC==1005 & duree_mee100X!=. //this is only defined for those who do have a case
		estadd scalar premean=r(mean)
		estadd scalar presd=r(sd)
		*IV, continuous
		xtivreg2 yyvatLOG (d100XXtreat = entafterTXXtreat treat) `fe'mth? `fe'mth?? if duree_mee100X!=., fe rf first cluster(ninea)
		est store IV2
		estadd local FE1 `e(ivar)'
		estadd local FE2 `fe'mth
		*FS, continuous
		xtreg d100XXtreat entafterTXXtreat treat `fe'mth? `fe'mth?? if duree_mee100X!=., fe cluster(ninea)
		est store FS2
		estadd local FE1 `e(ivar)'
		estadd local FE2 `fe'mth
		test entafterTXXtreat treat
		estadd scalar Fstat `r(F)'
		qui sum duree_mee100 if mthafterC==1005 & duree_mee100X!=. //this is only defined for those who do have a case
		estadd scalar premean=r(mean)
		estadd scalar presd=r(sd)

		*create table
			#delimit;
				estout case OLS IV FS RF OLS2 IV2 FS2 using "Tables\table5.tex", replace
				cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
				modelwidth(14) collabels(none) label mlabels("OLS" "OLS" "IV" "FS" "RF" "OLS" "IV" "FS", depvars) 
				numbers wrap varwidth(23) varlabels(_cons "Constant" treat "After pre-trial starts" meein4XXtreat "After pre-trial starts X Fast pre-trial" entafterTXXtreat "After pre-trial starts X After decree ($\gamma_1$)" meein4 "Fast pre-trial" d100XXtreat "After pre-trial starts X Pre-trial duration (in 100 days)" entafterT "After decree") 
				mgroups("Model 1" "Model 2" "Model 3", pattern(1 1 0 0 0 1 0 0) span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cline{3-6} \cline{8-10})) extracols(6)
				order(treat meein4XXtreat d100XXtreat)
				drop(*`fe'mth* _cons) `exp'
				stats(coef pval FE1 FE2 premean presd Fstat N, fmt(%5.2f %5.2f %~3s %~3s %10.2f %10.2f %5.2g %5.0f) 
					labels("Effect if fast pre-trial" "P-value: effect if fast pre-trial" "FEs" "Time FEs" "Pre-mean" "Pre-sd" "Fstat excl inst" "Observations"))
				prehead(
				\centering \begin{threeparttable} 
						\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *5{>{\centering\arraybackslash}p{1.6cm}} *1{>{\centering\arraybackslash}p{0.1cm}} *3{>{\centering\arraybackslash}p{1.6cm}}} \hline \hline) 
				posthead(\hline) prefoot(\hline) 
				postfoot(\hline \hline \end{tabular} 
				`tablenotes5'
				\end{threeparttable} 
				) 
				;
			#delimit cr
	}
	
	if "`i'"=="A12"{
	   
	   *create table
		#delimit;
			estout case OLS IV FS RF using "Tables\tableA12.tex", replace
			cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
			modelwidth(14) collabels(none) label mlabels("OLS" "OLS" "IV" "FS" "RF", depvars) numbers wrap varwidth(23) varlabels(_cons "Constant" treat "After pre-trial starts" meein4XXtreat "After pre-trial starts X Fast pre-trial" entafterTXXtreat "After pre-trial starts X After decree ($\gamma_1$)" meein4 "Fast pre-trial" entafterT "After decree") 
			mgroups("Model 1" "Model 2", pattern(1 1 0 0 0) span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cline{3-6}))
			drop(*`fe'mth* _cons) `exp'
			stats(coef pval FE1 FE2 premean presd Fstat N, fmt(%5.2f %5.2f %~3s %~3s %10.2f %10.2f %5.2g %5.0f) 
				labels("Effect if fast pre-trial" "P-value: effect if fast pre-trial" "FEs" "Time FEs" "Pre-mean" "Pre-sd" "Fstat excl inst" "Observations"))
			prehead(
			\centering \begin{threeparttable} 
					\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
			posthead(\hline) prefoot(\hline) 
			postfoot(\hline \hline \end{tabular} 
			`tablenotesA12'
			\end{threeparttable} 
			) 
			;
		#delimit cr
	}
}

*/


* TABLE A1 (CHAMBER-LEVEL CASELOAD)
***********************************

use "Data\SoJhearings", clear

collapse (mean) numin nummee numaftermee, by(code_chambre an)
reshape wide numin nummee numaftermee, i(an) j(code_chambre)
foreach k in numin nummee numaftermee{
	foreach v in 44 45 46 47 83 84 85{
		rename `k'`v' `k'C`v'
	}
}
reshape long @C44 @C45 @C46 @C47 @C83 @C84 @C85, i(an) j(cat "numin" "nummee" "numaftermee")

foreach i in numin nummee numaftermee{
	estpost tabstat C?? if cat=="`i'", by(an) nototal columns(variables) stat(min)
	est sto `i'
}

#delimit;
	estout numin using "Tables\tableA1.tex", replace
	cells("C44 (fmt(%012.1fc)) C45 (fmt(%012.1fc)) C46 (fmt(%012.1fc)) C47 (fmt(%012.1fc)) C83 (fmt(%012.1fc)) C84 (fmt(%012.1fc)) C85 (fmt(%012.1fc))") delim("&") style(tex) 
	modelwidth(14) collabels("1st Commercial" "2nd Commercial" "3rd Commercial" "4th Commercial" "1st Civil" "2nd Civil" "3rd Civil") mlabels(,none) wrap
	varlabels(2012 "Average number" 2013 "of incoming cases" 2014 "per hearing" 2015 " ") labcol2(2012 2013 2014 2015, title(""))
	prehead(\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.6pt} \begin{tabular}{l *{8}{>{\centering\arraybackslash}p{1.6cm}}} \hline \hline) 
	posthead(\hline)
;
	estout nummee using "Tables\tableA1.tex", append
	cells("C44 (fmt(%012.1fc)) C45 (fmt(%012.1fc)) C46 (fmt(%012.1fc)) C47 (fmt(%012.1fc)) C83 (fmt(%012.1fc)) C84 (fmt(%012.1fc)) C85 (fmt(%012.1fc))") delim("&") style(tex) 
	modelwidth(14) collabels(,none) mlabels(,none) label wrap
	varlabels(2012 "Average number" 2013 "of ongoing cases" 2014 "in pre-trial" 2015 " ") labcol2(2012 2013 2014 2015, title(""))
	posthead(\hline)
;
	estout numaftermee using "Tables\tableA1.tex", append
	cells("C44 (fmt(%012.1fc)) C45 (fmt(%012.1fc)) C46 (fmt(%012.1fc)) C47 (fmt(%012.1fc)) C83 (fmt(%012.1fc)) C84 (fmt(%012.1fc)) C85 (fmt(%012.1fc))") delim("&") style(tex) 
	modelwidth(14) collabels(,none) mlabels(,none) label wrap
	varlabels(2012 "Average number" 2013 "of ongoing cases" 2014 "in decision stage" 2015 " ") labcol2(2012 2013 2014 2015, title(""))
	posthead(\hline)
	postfoot("\hline \hline \end{tabular}
	`tablenotesA1' 
	 \end{threeparttable} 
	")
;
#delimit cr



* TABLES A2, A3, A8, A9, A10, A17:
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

label var delibwopt "Fast-tracked"
label var montabm "Above median claim amount"
label var typecommercial "Commercial case"
label var article_num "Number of articles"
label var taille_rel_surce "Decision length"
label var dummy_exp "Appeal"
gen _t=. //to ensure the duration model colums get labelled

local table_A2 duree_mee_B durmod_B meein4_B deskrej_B delibwopt_B numaudmee_B shheardmee_B ferme_among_renvoi_B
local table_A3 duree_mee_A durmod_A meein4_A deskrej_A delibwopt_A numaudmee_A shheardmee_A ferme_among_renvoi_A
local table_A8 duree_decision_B durdec_B decisionin1_B numaudaftermee_B shheardaftermee_B
local table_A9 duree_decision_A durdec_A decisionin1_A numaudaftermee_A shheardaftermee_A
local table_A10 aftermee_hasrab_A aftermee_haspro_A article_num_A taille_rel_surce_A dummy_exp_A
local table_A17 numin_A montabm_A moredemordef_A typecommercial_A 
*removed istca2012_A0, istca2012_A1, istca2012_A2 here as they cannot be included in the replication data


foreach i in A2 A3 A8 A9 A10 A17 {
	local exp
	if "`i'"=="A2" | "`i'"=="A3"{
		local exp "eform(0 1 0 0 0 0 0 0)" /*to show hazard ratios instead of beta coefficients for the duration models*/
		label var _t "Hazard ratio - finishing pre-trial"
	}
	if "`i'"=="A9" | "`i'"=="A10"{
		local exp "eform(0 1 0 0 0)" /*to show hazard ratios instead of beta coefficients for the duration models*/
		label var _t "Hazard ratio - finishing decision stage"
	}
	local robustlab
	if "`i'"=="A17"{
		local robustlab `"`"Number of incoming cases"' `"Above median claim"' `"More parties"' `"Commercial cases"' `"2012 revenues (IHS transf.)"' `"2012 revenues (IHST, plaintiff)"' `"2012 revenues (IHST, defendant)"'"' 
	}
	#delimit;
		estout `table_`i'' using "Tables\table`i'.tex", replace
		cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
		modelwidth(14) collabels(none) label mlabels(`robustlab',depvars) numbers wrap varlabels(_cons "Constant" 1.entafterT "Entered after decree application ($\beta$)" tentafterT "Trend" tsinceTa "Trend" 1.entafterT#c.tentafterT "Interaction" 1.audafterTa "Hearing after decree application" c.tsinceTa "Trend" 1.audafterTa#c.tsinceTa "Interaction" numin "Number of incoming cases") 
		drop(*0.* *calmth* *code_chambre* _cons) `exp'
		stats(bootp FE1 FE2 woadj premean presd r2 N, fmt(%5.2f %~3s %~3s %~3s %5.2f %5.2f %5.2f %5.0f) labels("P-value 6pWCBoot" "Chamber FEs" "Calendar month FEs" "Without adj. period" "Pre-mean" "Pre-sd" "R-Squared" "Observations"))
		prehead(
		\centering \begin{threeparttable} 
				\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
		posthead(\hline) prefoot(\hline) 
		postfoot(\hline \hline \end{tabular} 
		`tablenotes`i''
		\end{threeparttable} 
		) 
		;
	#delimit cr
}


* TABLE A4:
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

label var delibwopt "Fast-tracked"
local table_A4 duree_mee_C meein4_C deskrej_C delibwopt_C numaudmee_C shheardmee_C ferme_among_renvoi_C
#delimit;
	estout `table_A4' using "Tables\tableA4.tex", replace
	cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
	modelwidth(14) collabels(none) label mlabels(, depvars) numbers wrap 
	varlabels(_cons "Constant" 1.entafterT "Entered after decree application" tentafterT "Trend" 
			1.entafterT#c.tentafterT "Entered after decree application X Trend"  
			1.montabm "Above median claim" 1.montabm#1.entafterT "Above median claim X Entered after decree" 
			1.montabm#c.tentafterT "Above median claim X Trend" 1.montabm#1.entafterT#c.tentafterT "Triple interaction") 
	drop(*0.* *entcalmth *code_chambre2 _cons)
	stats(bootp coef pval bootp2 FE1 FE2 woadj premean presd r2 N, fmt(%5.2f %5.2f %5.2f %5.2f %~3s %~3s %~3s %5.2f %5.2f %5.2f %5.0f) 
	labels("P-value 6pWCBoot: entered after" "Effect for large cases" "P-value: effect for large cases" "P-value 6pWCB: large cases" "Chamber FEs" "Calendar month FEs" "Without adjustment period" "Pre-mean" "Pre-sd" "R-Squared" "Observations"))
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
	posthead(\hline) prefoot(\hline) 
	postfoot(\hline \hline \end{tabular} 
	`tablenotesA4'
			\end{threeparttable} 
			) 
	;
#delimit cr


* TABLE A5:
********************************

local table_A5 duree_mee_FD meein4_FD deskrej_FD delibwopt_FD numaudmee_FD shheardmee_FD ferme_among_renvoi_FD
#delimit;
	estout `table_A5' using "Tables\tableA5.tex", replace
	cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
	modelwidth(14) collabels(none) label mlabels(, depvars) numbers wrap 
	varlabels(_cons "Constant" 1.entafterT "Entered after decree application" 1.magspeedabm "Fast judge" 
			1.magspeedabm#1.entafterT "Fast judge X Entered after decree appl." 
			1.magspeedabm#c.tentafterT "Fast judge X Trend" 1.magspeedabm#1.entafterT#c.tentafterT "Triple interaction"
			magcolleg3 "Collegial pre-trial")
	drop(*mont_quint2 *0.* *calmth* *code_chambre* tentafterT 1.entafterT#c.tentafterT _cons)
	stats(bootp coef pval bootp2 FE1 FE2 FE3 woadj premean presd r2 N, fmt(%5.2f %5.2f %5.2f %5.2f %~3s %~3s %~3s %~3s %5.2f %5.2f %5.2f %5.0f) 
	labels("P-value 6pWCBoot: entered after" "Effect for fast judges" "P-value: effect for fast judges" "P-value 6pWCBoot: fast judges" "Chamber FEs x Trend" "Calendar month FEs" "Amount category controls" "Without adjustment period" "Comparison mean" "Comparison sd" "R-Squared" "Observations"))
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
	posthead(\hline) prefoot(\hline) 
	postfoot(\hline \hline \end{tabular} 
			`tablenotesA5'
			\end{threeparttable} 
			) 
	;
#delimit cr


* TABLE A11 (NEGATIVE CASE IMPLICATIONS)
********************************

use "Data\SoJfirmsurvey.dta", replace

quietly estpost tabstat demamtspent demhrslost demamthrslost demdebt demnoinvest demcourtagain, col(stat) stat(n median mean sd min max)  
eststo fsplaintiff

quietly estpost tabstat defamtspent defhrslost defamthrslost defdebt defnoinvest, col(stat) stat(n median mean sd min max)  
eststo fsdefendant

#delimit;
	estout fsplaintiff using "Tables\tableA11.tex", replace
	cells("count mean(fmt(%012.2fc)) sd(fmt(%012.2fc)) p50(fmt(%012.2fc)) min(fmt(%012.2fc)) max(fmt(%012.2fc))") delim("&") style(tex) 
	modelwidth(14) collabels(N Mean StD Median Min Max) mlabels(,none) label wrap
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{7}{>{\centering\arraybackslash}p{1.4cm}}} \hline \hline) 
	posthead(\hline "PANEL A: Firms with case(s) as plaintiff & & & \\" "& & & \\") 
;
	estout fsdefendant using "Tables\tableA11.tex", append
	cells("count mean(fmt(%012.2fc)) sd(fmt(%012.3fc)) p50(fmt(%012.2fc)) min(fmt(%012.2fc)) max(fmt(%012.2fc))") delim("&") style(tex) 
	modelwidth(14) collabels(,none) mlabels(,none) label wrap
	posthead("& & & \\" \hline "PANEL B Firms with case(s) as defendant: & & & \\" "& & & \\") 
	postfoot("\hline \hline \end{tabular}
	`tablenotesA11' 
	 \end{threeparttable} 
	")
;
#delimit cr



* TABLE A13: ANCOVA, TAX DATA (not included in replication file)
********************************
/*
use "$taxlocation\vatrevenues.dta", clear

drop if side==0 //only firms with a case

local yyvatLOGM02 yyvatLOGM01 yyvatLOGM02 yyvatLOGM03 yyvatLOGM04 yyvatLOGM05 yyvatLOGM06

*OLS
reg yyvatLOGavg meein4 ib1.calmth ib44.code_chambre2 `yyvatLOGM02'  if mthafterC==1005, cluster(cham2_tentry)
est store OLS
estadd local FE1 chamber
estadd local FE2 calmth
qui sum yyvatLOGM01 if mthafterC==1005
estadd scalar premean=r(mean)
estadd scalar presd=r(sd)
*IV
ivregress 2sls yyvatLOGavg (meein4=entafterT) ib1.calmth ib44.code_chambre2 `yyvatLOGM02'  if mthafterC==1005, cluster(cham2_tentry)
est store IV
estadd local FE1 chamber
estadd local FE2 calmth
*RF
reg yyvatLOGavg entafterT ib1.calmth ib44.code_chambre2 `yyvatLOGM02'  if mthafterC==1005, cluster(cham2_tentry)
est store RF
estadd local FE1 chamber
estadd local FE2 calmth
*FS
reg meein4 entafterT ib1.calmth ib44.code_chambre2 `yyvatLOGM02'  if mthafterC==1005, cluster(cham2_tentry)
est store FS
estadd local FE1 chamber
estadd local FE2 calmth
test entafter
estadd scalar Fstat `r(F)'

*OLS-continuous
reg yyvatLOGavg duree_mee100 ib1.calmth ib44.code_chambre2 `yyvatLOGM02'  if mthafterC==1005 & duree_mee100!=., cluster(cham2_tentry)
est store OLS2
estadd local FE1 chamber
estadd local FE2 calmth
qui sum yyvatLOGM01 if mthafterC==1005 & duree_mee100!=.
estadd scalar premean=r(mean)
estadd scalar presd=r(sd)
*IV-continuous
ivregress 2sls yyvatLOGavg (duree_mee100=entafterT) ib1.calmth ib44.code_chambre2 `yyvatLOGM02'  if mthafterC==1005 & duree_mee100!=., cluster(cham2_tentry)
est store IV2
estadd local FE1 chamber
estadd local FE2 calmth
*FS-continuous
reg duree_mee100 entafterT ib1.calmth ib44.code_chambre2 `yyvatLOGM02'  if mthafterC==1005 & duree_mee100!=., cluster(cham2_tentry)
est store FS2
estadd local FE1 chamber
estadd local FE2 calmth
test entafter
estadd scalar Fstat `r(F)'

*create table
	#delimit;
		estout OLS IV FS RF OLS2 IV2 FS2 using "Tables\tableA13.tex", replace
		cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
		modelwidth(14) collabels(none) label mlabels("OLS" "IV" "FS" "RF" "OLS" "IV" "FS", depvars) 
		numbers wrap varwidth(23) order(meein4 duree_mee100 entafterT) varlabels(_cons "Constant" treat "treat" meein4 "Fast pre-trial" entafterT "After decree" duree_mee100 "Pre-trial duration (in 100 days)") 
		mgroups("Model 2" "Model 3", pattern(1 0 0 0 1 0 0) span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cline{2-5} \cline{7-9})) extracols(5)
		drop(*calmth* *code_chambre* _cons) `exp'
		stats(FE1 FE2 premean presd Fstat N, fmt(%~3s %~3s %10.2f %10.2f %5.2g %5.0f) labels("FEs" "Time FEs" "Pre-mean" "Pre-sd" "Fstat excl inst" "Observations"))
		prehead(
		\centering \begin{threeparttable} 
				\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *4{>{\centering\arraybackslash}p{1.6cm}} *1{>{\centering\arraybackslash}p{0.1cm}} *3{>{\centering\arraybackslash}p{1.6cm}}} \hline \hline) 
		posthead(\hline) prefoot(\hline) 
		postfoot(\hline \hline \end{tabular} 
		`tablenotesA13'
		\end{threeparttable} 
		) 
		;
	#delimit cr

*/


*TABLE A14 (PERCEPTION)
********************************

use "Data\SoJfirmsurvey.dta", clear

label var estspeedW "Duration"
label var estcostW "Costs (in 1000 FCFA)"
label var hypsmall "Hypothe- tical"
label var perscore "Perception index"

foreach i in firmempBL{ //to avoid dropping obs because of missing covariates
	gen `i'XXX=`i'
	gen `i'MMM=0
	replace `i'MMM=1 if mi(`i')
	replace `i'XXX=0 if mi(`i')
}

local t1 treatc firmempBLXXX firmempBLMMM N
local t2 subtreatcN1 firmempBLXXX firmempBLMMM if N==1

est drop _all

foreach i in estspeedW estcostW hypsmall perscore{
	forval v=1/2{
		reg `i' `t`v'', robust
		est store `i't`v'
		qui sum `i' if treatc==0
		estadd scalar premean=r(mean)
	}
}

local table_A14 estspeedWt1 estspeedWt2 estcostWt1 estcostWt2 hypsmallt1 hypsmallt2 perscoret1 perscoret2

#delimit;
	estout `table_A14' using "Tables\tableA14.tex", replace 
	cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
	modelwidth(12) collabels(none) label mlabels(, depvar) numbers wrap 
	varlabels(_cons "Constant" treatc "Case(s) after decree applic." subtreatcN1 "Case after decree applic." N "Number of cases")
	drop(firmempBLXXX firmempBLMMM _cons)
	order(treatc subtreatcN1 firmempBLXXX N)
	stats(premean r2 N, fmt(%5.2f %5.2f %5.0f) 
	labels("Pre-mean" "R-Squared" "Observations"))
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.3pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.7cm}}} \hline \hline) 
	posthead(\hline) prefoot(\hline) 
	postfoot(\hline \hline \end{tabular}
			`tablenotesA14'
			\end{threeparttable} 
			) 
	;
#delimit cr



* TABLE A15 (BALANCE ON BL CHARACTERISTICS)
********************************

use "Data\SoJfirmparties.dta", clear

#delimit; 
balancetable invatanalysis entafterT side1 montabm 
	using "Tables\tableA15.tex", replace cov(i.code_chambre2 i.entcalmth) 
	vce(cluster cham2_tentry) observationscolumn noobs varlabels
	ctitles("Court-" "In ..." "Difference" "Obser-") format(%8.2f)
	posthead(" & only & sample & (2)-(1) & vations \\" "\hline PANEL A: Tax record sample (party level) & & & & \\ & & & & \\") 
	nofoot
;
#delimit cr
*montant1 removed for anonymization; istca2012 removed as it cannot be included in the replication data

keep if withinfirmid==1

#delimit;
balancetable invatanalysisA2 entafterTA side1A Nobs
	using "Tables\tableA15.tex", append cov(i.code_chambre2 i.entcalmth) 
	vce(cluster cham2_tentry) observationscolumn noobs varlabels 
	nohead nofoot format(%8.2f)
	posthead("\hline PANEL B: Tax record sample (firm level) & & & & \\ & & & & \\") 
;
#delimit cr
*montant1A removed for anonymization; istca2012 removed as it cannot be included in the replication data

#delimit;
balancetable infirmsurvey entafterTA side1A Nobs
	using "Tables\tableA15.tex", append cov(i.code_chambre2 i.entcalmth) 
	vce(cluster cham2_tentry) observationscolumn noobs varlabels 
	nohead format(%8.2f)
	posthead("\hline PANEL C: Firm survey sample (firm level) & & & & \\ & & & & \\")
	postfoot("\hline \hline"
	"\multicolumn{5}{l}{\underline{Notes}: Balance on baseline characteristics, Panel A: comparing case parties across court-only} \\" 
	"\multicolumn{5}{l}{and tax record sample; Panel B: comparing court-only firms with those that have at least one} \\" 
	"\multicolumn{5}{l}{party in the tax record sample; Panel C: comparing firms across court-only and firm survey} \\"  
	"\multicolumn{5}{l}{sample. Number of observations in sample (Column 2): Panel A 1622; Panel B 582; Panel C} \\" 
	"\multicolumn{5}{l}{277. Columns (1) and (2) show raw means and standard deviations (in parentheses); Column} \\" 
	"\multicolumn{5}{l}{(3) shows the regression adjusted difference including chamber and calendar month fixed effects,} \\" 
	"\multicolumn{5}{l}{standard errors in parentheses, clustered at the (chamber x hearing of entry) level. Significance} \\" 
	"\multicolumn{5}{l}{levels are denoted as follows: * p$<$0.10, ** p$<$0.05, *** p$<$0.01.} \\"  
	"\end{tabular}")
;
#delimit cr
*montant1A removed for anonymization; istca2012 removed as it cannot be included in the replication data



* TABLE A16 (BALANCE ON EFFECT SIZE)
********************************

use "Data\SoJfirmparties.dta", clear

gen insample=invatanalysis
gen treatment=entafterT

foreach outcome in meein4 duree_mee dummy_exp{
	reg `outcome' i.invatanalysis##i.entafterT ib44.code_chambre2 ib1.entcalmth, cluster(cham2_tentry)
	eststo fp`outcome'
	estadd local FE1 Yes
	estadd local FE2 Yes
	preserve 
		lincomest (1.entafterT+1.invatanalysis#1.entafterT)
		parmest, norestore
		format p estimate stderr %5.2f
		levelsof p if(_n==1), local(p)
		levelsof estimate if(_n==1), local(estimate)
		levelsof stderr if(_n==1), local(stderr)
	restore
	est resto fp`e(depvar)'
	estadd scalar pval=round(`p',.01)
	estadd scalar coef=round(`estimate',.01)
	estadd scalar se=round(`stderr',.01)
}

keep if withinfirmid==1

/*commented out as istca2012 cannot be included in the replication data
foreach i in istca2012{ //to avoid dropping obs because of missing covariates
	gen `i'XXX=`i'
	gen `i'MMM=0
	replace `i'MMM=1 if mi(`i')
	replace `i'XXX=0 if mi(`i')
}

foreach i in meein4A duree_meeA dummy_expA{
	reg `i' i.infirmsurvey##i.entafterTA2 Nobs istca2012XXX istca2012MMM, robust
	eststo fsurv`i'
	estadd local FE1 Yes
	estadd local FE2 Yes
	preserve 
		lincomest (1.entafterTA2+1.infirmsurvey#1.entafterTA2)
		parmest, norestore
		format p estimate stderr %5.2f
		levelsof p if(_n==1), local(p)
		levelsof estimate if(_n==1), local(estimate)
		levelsof stderr if(_n==1), local(stderr)
	restore
	est resto fsurv`e(depvar)'
	estadd scalar pval=round(`p',.01)
	estadd scalar coef=round(`estimate',.01)
	estadd scalar se=round(`stderr',.01)
}
*/
local tableA16 fpmeein4 fpduree_mee fpdummy_exp 
*fsurvmeein4A fsurvduree_meeA fsurvdummy_expA removed due to the above commenting-out

#delimit;
	estout `table_A16' using "Tables\tableA16.tex", replace
	cells(b($star fmt(%10.2f)) se(par)) delim("&") style(tex) starlevels(* 0.1 ** 0.05 *** 0.01) 
	modelwidth(14) collabels(none) label mlabels(, depvars) numbers wrap 
	mgroups("Panel A: Tax record sample (party level) " "Panel B: Firm survey sample (firm level)", span pattern(1 0 0 1 0 0) prefix(\multicolumn{@span}{c}{) suffix(}))
	varlabels(_cons "Constant"  
		1.invatanalysis#1.entafterT "In tax record sample X Entered after"
		1.infirmsurvey#1.entafterTA2 "In survey sample X Case(s) after"
		1.invatanalysis "In tax record sample"
		1.infirmsurvey "In survey sample"
		1.entafterT "Entered after decree application"
		1.entafterTA2 "Case(s) after decree application"
		)
	drop(*0.* *calmth* *code_chambre* _cons)
	stats(coef pval FE1 FE2 r2 N, fmt(%5.2f %5.2f %~3s %~3s %5.2f %5.0f) 
	labels("Effect if in sample" "P-value: effect if in sample" "Chamber FEs" "Calendar month FEs" "R-Squared" "Observations"))
	prehead(
			\centering \begin{threeparttable} 
			\setlength{\tabcolsep}{1.5pt} \begin{tabular}{l *{@E}{>{\centering\arraybackslash}p{1.9cm}}} \hline \hline) 
	posthead(\hline) 
	prefoot(\hline) 
	postfoot(\hline \hline \end{tabular} 
	`tablenotesA16'
			\end{threeparttable})
;
#delimit cr
* removed *istca2012* and Nobs from drop() due to the above commenting-out





********************************
* 5. FIGURES
********************************

* FIGURE 1 (TIMELINE)
********************************

use "Data\SoJhearings", clear

global graph_opts ///
		title(, justification(left) color(black) span pos(11)) ///
		graphregion(color(white) lc(white) lw(med)) ///
		ylab(,angle(0) nogrid) xtit(,placement(left) justification(left)) ///
		yscale(noline) xscale(noline) legend(region(lc(none) fc(none)))

#delimit ;

	twoway
	
	(pci 1160 0 1160 74 , color(navy) lp(dash) lwidth(thick)) //43->0, 117->74 (=jan2012 to jun2015)
	(pci 1000 0 1000 74 , color(black) lp(dot) lwidth(thick))
	(pci 840  0 840  74 , color(navy) lp(dash) lwidth(thick))
	(pci 680  21 680 49  , color(emidblue) lp(#_-_) lwidth(thick)) //64->21, 92->49 (=jan2013 to apr2014)
	(pci 520  0 520  74 , color(cranberry) lp(shortdash) lwidth(thick))
	(pci 360  0 360  34  , color(gold) lp(shortdash_dot) lwidth(thick)) //77->34 (=jan2012 to jul2013)
	(pci 200  17 200 74 , color(dkorange) lp(longdash_dot) lwidth(thick)) //60->17
	if t>=43
	, 
	${graph_opts} xsize(7)
	xtitle("hearing period {&rarr}") xlabel(0(5)73, valuelabel) //43(5)116 -> 0(5)73
	xline(38, lcolor(cranberry) lpattern(shortdash)) //81->38
	xline(41, lcolor(black) lpattern(dot)) //84->41
	xline(44, lcolor(navy) lpattern(dash)) //87->44
	xline(45, lcolor(emidblue) lpattern(#_-_)) //88->45
	xline(46, lcolor(dkorange) lpattern(longdash_dot)) //89->46
	ytitle("") ylabel(0(1400)1400, nolab noticks nogrid labcolor(gs15)) 
	legend(
		c(1) pos(3)  
		order(1 "1st Commercial (early Feb 2014)" 2 "2nd Commercial (Dec 2013)" 3 "3rd Commercial (early Feb 2014)" 4 "4th Commercial (late Feb 2014)" 0 " " 5 "1st Civil (Nov 2013)" 6 "2nd Civil (N/A)" 7 "3rd Civil (March 2014)") 
		colfirst
	) ;
#delimit cr
	
graph export "Figures\figure1.pdf", replace



* FIGURES 2-5
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

*Figure 2, Panels A&C:
local title_duree_mee "A. Duration (days), size(medium)"
local title_meein4 "C. Likelihood of concluding in 4 months, size(medium)"

*Figure 3:
local title_deskrej "A. Likelihood of desk rejection, size(medium)"
local title_delibwopt "B. Likelihood of fast-tracked, size(medium)"
local title_numaudmee "C. Number of hearings, size(medium)"
local title_shheardmee "D. Likelihood of being heard, size(medium)"
local title_ferme_among_renvoi "E. Share judge strict, size(medium)"

*Figure 4, Panels A-E:
local title_duree_decision "A. Decision duration (days), size(medium)"
local title_decisionin1 "C. Likelihood of completion in 1 month, size(medium)"
local title_numaudaftermee "D. Number of hearings, size(medium)"
local title_shheardaftermee "E. Likelihood of being heard, size(medium)"

*Figure 5:
local title_aftermee_hasrab "A. Pre-trial insufficient, size(medium)"
local title_aftermee_haspro "B. Decision post-poned, size(medium)"
local title_article_num "C. Number of articles cited, size(medium)"
local title_taille_rel_surce "D. Length of decision justification, size(medium)"
local title_dummy_exp "E. Intention to appeal, size(medium)"

replace tentafterT=tentafterT+1000 
foreach var in duree_mee meein4 deskrej delibwopt numaudmee shheardmee ferme_among_renvoi duree_decision decisionin1 numaudaftermee shheardaftermee aftermee_hasrab aftermee_haspro article_num taille_rel_surce dummy_exp{
	reg `var' ib996.tentafterT ib1.entcalmth ib44.code_chambre2, cluster(cham2_tentry)
	mygraphP tentafterT, save(`var') options("xlabel(-40(8)20) title(`title_`var'') xtitle(chamber entry period)") xl(1) recode(1)
}
replace tentafterT=tentafterT-1000


cd ".\Figures"

*Figure 2 (pre-trial duration)
local gph
foreach i in duree_mee durmodmee meein4{
	local gph `gph' Graph_tentafterT_`i'.gph
}
graph combine `gph' "figure2D", scheme(s2mono) altshrink 
graph export "figure2.pdf", replace

*Figure 3 (pre-trial mechanisms)
local gph
foreach i in deskrej delibwopt numaudmee shheardmee ferme_among_renvoi{
	local gph `gph' Graph_tentafterT_`i'.gph
}
graph combine `gph', scheme(s2mono) altshrink 
graph export "figure3.pdf", replace

*Figure 4 (decision stage)
local gph
foreach i in duree_decision durmoddec decisionin1 numaudaftermee shheardaftermee{
	local gph `gph' Graph_tentafterT_`i'.gph
}
graph combine `gph' "figure4F", scheme(s2mono) altshrink 
graph export "figure4.pdf", replace

*Figure 5 (quality)
local gph
foreach i in aftermee_hasrab aftermee_haspro article_num taille_rel_surce dummy_exp{
	local gph `gph' Graph_tentafterT_`i'.gph
}
graph combine `gph', scheme(s2mono) altshrink 
graph export "figure5.pdf", replace

cd ..



* FIGURES 6 & A13 -- tax data, not in replication files
********************************

/*
use "$taxlocation\vatrevenues.dta", clear

*Figure 6, Panel A
areg yyvatLOG ib999.mthafterCX i.yrmth, cluster(ninea) a(partyid)
mygraphP mthafterCX, save(figure6A) options("xlabel(-7(1)6) xtitle(month relative to start of pre-trial) title(A. Overall, size(medium))") recode(1)

*Figure 6, Panel B
*mee4mthafterCX999, meeMmthafterCX999 are dropped from the dataset (omitted categories)
areg yyvatLOG mee4mthafterCX994-mee4mthafterCX1005 meeMmthafterCX994-meeMmthafterCX1005 ib650.yrmth, cluster(ninea) a(partyid)
mygraphP2 mthafterCX, save(figure6B) options("xlabel(-7(1)6) xtitle(month relative to start of pre-trial) title(B. By pre-trial speed, size(medium))")  lab1(Fast_pretrial) lab0(Slow_pretrial) type1(mee4) recode(1)

*Figure A13
*side1mthafterCX999, side2mthafterCX999 are dropped from the dataset (omitted categories)
areg yyvatLOG side1mthafterCX994-side1mthafterCX1005 side2mthafterCX994-side2mthafterCX1005 ib650.yrmth, cluster(ninea) a(partyid)
mygraphP2 mthafterCX, save(figureA13) options("xlabel(-7(1)6) xtitle(month relative to start of pretrial) title(By side, size(medium))")  lab1(Plaintiff) lab0(Defendant) type1(side1) recode(1)

cd ".\Figures"

*figure 6
graph combine Graph_mthafterCX_figure6A.gph Graph_mthafterCX_figure6B.gph, scheme(s2mono) altshrink ycommon ysize(2.75) xsize(6.25)
graph export "figure6.pdf", replace

*figure A13
graph combine Graph_mthafterCX_figureA13.gph, scheme(s2mono) altshrink ysize(2.75) xsize(3.13)
graph export "figureA13.pdf", replace


local gphlist: dir "`c(pwd)'" files "*.gph"
foreach i of local gphlist{
	erase `i'
}

cd ..

*/


* FIGURE 7 (WILLINGNESS TO PAY)
********************************

use "Data\SoJfirmsurvey.dta", clear

sum wtp_5mo wtp_3pt5mo
ttest wtp_5mo=wtp_3pt5mo
local meandiff=(r(mu_2)-r(mu_1))/1000000
local meandiff:  di %4.3f `meandiff'
local pval:  di %4.3f r(p) 
	 
preserve
	keep wtp_5mo 
	rename wtp_5mo wtp
	gen grp=1
	tempfile t1
	save `t1', replace
restore
keep wtp_3pt5mo
rename wtp_3pt5mo wtp
gen grp=2
append using `t1'
label define grp 1 "Pre-reform" 2 "Post-reform"
label val grp grp
	
replace wtp=wtp/1000000
kdensity wtp if grp==1 & wtp>=0 & wtp<8,   ///
	 addplot(kdensity wtp if grp==2 & wtp>=0 & wtp<8, legend(label (1 "Pre-reform avg. duration (5 months)") label(2 "Post-reform avg. duration (3.5 months)"))) xtitle("") xtitle(mio FCFA) title("") ytitle("") ///
	 text( 1.3 3 "Mean difference: `meandiff' million FCFA" 1.2 3  "P-value = `pval'") note("") scheme(s2mono)
graph export "Figures\figure7.pdf", replace


* FIGURE A2 (COURT-LEVEL CASELOAD)
********************************

use "Data\SoJhearings", clear

global graph_opts ///
		title(, justification(left) color(black) span pos(11)) ///
		graphregion(color(white) lc(white) lw(med)) ///
		ylab(,angle(0) nogrid) xtit(,placement(left) justification(left)) ///
		yscale(noline) xscale(noline) legend(region(lc(none) fc(none)))	


collapse (sum) numongoing numin numout, by(t)
local v=43
forval i=0/73{
	label define tlab `v' "`i'", modify
	local v=`v'+1
}
label values t tlab
twoway (line numin t, color(black)) (line numongoing t, color(gs10)) if t>=43, ${graph_opts} xtitle("hearing period {&rarr}") xlabel(43(4)116, valuelabel)  xline(81, lcolor(black)) xline(84, lcolor(black)) xline(87, lcolor(black)) xline(88, lcolor(black))  xline(89, lcolor(black)) ylabel(0(200)1500, angle(horizontal)) text(250 108 "Incoming") text(1250 108 "Ongoing") legend(off) scheme(s2mono)
graph export "Figures\figureA2.pdf", replace


* FIGURES A3 & A4 (CHAMBER-LEVEL)
********************************

use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

label define code_chambre2 44 "1st Commercial" 45 "2nd Commercial" 46 "3rd Commercial" 47 "4th Commercial" 83 "1st Civil" 84 "2nd Civil" 85 "3rd Civil"
label val code_chambre2 code_chambre2

*event study at the chamber-level: run the same model as the main one, removing the chamber-fixed effects
replace tentafterT=tentafterT+1000
foreach i in 44 45 46 47 83 85{
	local lab`i': label code_chambre2 `i'
	reg duree_mee ib996.tentafterT if code_chambre2==`i', cluster(cham2_tentry)
	mygraphP tentafterT, save(durmeeC`i') options("xlabel(-40(8)20) xtitle(chamber entry period) title(`lab`i'', size(medium))") xl(1) recode(1) noconfid(1)
	reg meein4 ib996.tentafterT if code_chambre2==`i', cluster(cham2_tentry)
	mygraphP tentafterT, save(meein4C`i') options("xlabel(-40(8)20) xtitle(chamber entry period) title(`lab`i'', size(medium))") xl(1) recode(1) noconfid(1)
}


use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

local chmodel1 i.entafterT##ib44.code_chambre2##c.tentafterT ib1.entcalmth, cluster(cham2_tentry)
local chmodel2 i.entafterT##ib44.code_chambre2##c.tentafterT ib1.entcalmth if $withoutadj, cluster(cham2_tentry)

#delimit ;

local flexmodel1 i.entafterT tentafterT i.entafterT#c.tentafterT ib44.code_chambre2#c.tentafterT 
	i.entafterT#ib44.code_chambre2#c.tentafterT ib44.code_chambre2 ib1.entcalmth, cluster(cham2_tentry);
local flexmodel2 i.entafterT tentafterT i.entafterT#c.tentafterT ib44.code_chambre2#c.tentafterT 
	i.entafterT#ib44.code_chambre2#c.tentafterT ib44.code_chambre2 ib1.entcalmth if $withoutadj, cluster(cham2_tentry);

#delimit cr

local lduree_mee A.
local lmeein4 B.
forval mod=1/2{
	foreach i in duree_mee meein4{
		local lab`i': variable label `i'
		reg `i' `flexmodel`mod''
		est store fullmodel
		reg `i' `chmodel`mod''
		est store main
		
		lincomest 1.entafterT+1.entafterT#44b.code_chambre2
		est store ch44
		est restore main
		foreach v in 45 46 83 85{
			lincomest 1.entafterT+1.entafterT#`v'.code_chambre2
			est store ch`v'
			est restore main
		}
		coefplot (fullmodel, keep(1.entafterT) rename(1.entafterT = "Combined") xtitle("chamber entry period") title("`l`i'' `lab`i''", size(medium))) ///
			   (ch44, rename((1) = "1st com") \ ch45, rename((1) = "2nd com") \  ch46, rename((1) = "3rd com") \  ///
				ch83, rename((1) = "1st civ") \ ch85, rename((1) = "3rd civ")) ///
				, legend(off) scheme(s2mono)   //see graph note for why 4th commercial is not in the graph
		graph save "Figures\Graph_chamlevelavgeff_`i'_`mod'.gph", replace
		est drop fullmodel main ch??
	}	
}	

cd ".\Figures"

*Figure A3
local gph
foreach i in 44 45 46 47 83 85{
	local gph `gph' Graph_tentafterT_durmeeC`i'.gph
}
graph combine `gph', altshrink scheme(s2mono) ycommon xcommon
graph export "figureA3.pdf", replace

*Figure A4
graph combine "Graph_chamlevelavgeff_duree_mee_2.gph" "Graph_chamlevelavgeff_meein4_2.gph", scheme(s2mono)
graph export "figureA4.pdf", replace

cd ..


* FIGURE A5 (KERNEL DENSITY GRAPHS AROUND CUTOFF; R SCRIPT, RUNNING FROM STATA)
********************************

file open rcode using  "ridgeline_plot.R", write replace

file write rcode ///
	"rm(list=ls())" _n ///
	"PACKAGES <- $r_insall" _n  ///
	"packages  <- c('readstata13','foreign', 'ggridges', 'doBy', 'broom', 'dplyr', 'ggplot2', 'viridis')" _n ///
	"if (PACKAGES) {" _n ///
	  "install.packages(packages, dependencies = TRUE)" _n ///
	"}" _n ///
	"invisible(sapply(packages, library, character.only = TRUE))" _n ///
	"data           <- file.path('Data')" _n ///
	"figures      <- file.path('Figures')" _n ///
	"cases <- read.dta13(paste0(data, '\\SoJcases.dta'))" _n ///
	"breaks <- c(-38, -27, -22, -17, -12, -7, -2, 3, 8, 13, 21)" _n /// 
	"cases\$y_var <- cut(cases\$tentafterT, breaks," _n ///
	"include.highest = T, right = F," _n ///
	"labels = c('-38 to -26', '-27 to -21'," _n ///
	"'-20 to -16', '-15 to -10'," _n ///
	"'-10 to -6', '-5 to -1'," _n ///
	"'Decree start\n to T+5', '6 to 10'," _n ///
	"'11 to 15', '16 to 20'))" _n ///	
	"cases_plot <- subset(cases, select = c(tentafterT, y_var, duree_mee))" _n ///
	"cases_plot <- na.omit(cases_plot)" _n ///
	"ggplot(cases_plot, aes(x = duree_mee, y = y_var)) +" _n ///
		"geom_density_ridges(aes(fill = y_var)," _n ///
							"quantile_lines = T, quantiles = 1.5," _n ///
							"scale = 2," _n ///
							"rel_min_height = 0.01, jittered_points = TRUE," _n ///
							"position = position_points_jitter(width = 0.5, height = 0)," _n ///
							"point_shape = '|', point_size = 1," _n ///
							"alpha = 0.7) +" _n ///
		"theme_minimal() +" _n ///
		"scale_fill_manual(values = c('gray70', 'gray70'," _n ///
									 "'gray70', 'gray70'," _n ///
									 "'gray70', 'gray70'," _n ///
								     "'gray47', 'gray47'," _n ///
								     "'gray47', 'gray47'), guide = F) +" _n ///
		"xlab('Pre-trial duration') +" _n ///
		"ylab('Time of entry relative to degree application') +" _n ///
		"theme(plot.title = element_text(size=18, hjust= 0.5)," _n ///
			"axis.title.x = element_text(size=12)," _n ///
			"axis.title.y = element_text(size=12)," _n ///
			"axis.text = element_text(size=12)) +" _n ///
	"ggsave(filename='figureA5.pdf'," _n /// 
		   "device = 'pdf'," _n /// 
		   "path = figures)"
file close rcode

shell "$Rexe" --vanilla <"ridgeline_plot.R"


* FIGURES A6-A9 (PLACEBO TEST)
********************************

use "Data\SoJcases", clear //unlike for other models, do not restrict time window here (different running variable)

local title_duree_mee "A. Duration (days), size(medium)"
local title_meein4 "B. Likelihood of concluding in 4 months, size(medium)"
local title_deskrej "C. Desk rejection, size(medium)"
local title_ferme_among_renvoi "D. Judge more strict, size(medium)" 
local title_delibwopt "E. Likelihood of fast-tracked, size(medium)" 
local title_numaudmee "F. Number of hearings, size(medium)" 


* Run the first placebo test: leaving 1st civil out -- display all cutoffs
foreach var in duree_mee meein4 deskrej ferme_among_renvoi delibwopt numaudmee{
	reg `var' ib77.tentry ib44.code_chambre2  if code_chambre2!=83, cluster(cham2_tentry)
	mygraphP tentry, save(cutoff_`var'_1) options("xlabel(43(8)110, valuelabel) xtitle(chamber entry period) title(`title_`var'')") xl(3) recode(0)
}

* Run the second placebo test: leaving 1st civil and second commercial out -- display all cutoffs (red/dashed: do not apply; black: apply to some chambers)
foreach var in duree_mee meein4 deskrej ferme_among_renvoi delibwopt numaudmee{
	reg `var' ib77.tentry ib44.code_chambre2  if code_chambre2!=83&code_chambre2!=45, cluster(cham2_tentry)
	mygraphP tentry, save(cutoff_`var'_2) options("xlabel(43(8)110, valuelabel) xtitle(chamber entry period) title(`title_`var'')") xl(4) recode(0)
}

* Run the second placebo test: leaving 1st civil, second commercial, and 1st and 3rd commercial out -- display all cutoffs
foreach var in duree_mee meein4 deskrej ferme_among_renvoi delibwopt numaudmee{
	reg `var' ib77.tentry ib44.code_chambre2  if code_chambre2!=83&code_chambre2!=45&code_chambre2!=44&code_chambre2!=46, cluster(cham2_tentry)
	mygraphP tentry, save(cutoff_`var'_3) options("xlabel(43(8)110, valuelabel) xtitle(chamber entry period) title(`title_`var'')") noconfid(1) xl(5) recode(0)
}

* Run the second placebo test: leaving 1st civil, second commercial, 1st and 3rd commercial, and 4th commercial  out -- display all cutoffs
foreach var in duree_mee meein4 deskrej ferme_among_renvoi delibwopt numaudmee{
	reg `var' ib77.tentry ib44.code_chambre2  if code_chambre2!=83&code_chambre2!=45&code_chambre2!=44&code_chambre2!=46&code_chambre2!=47, cluster(cham2_tentry)
	mygraphP tentry, save(cutoff_`var'_4) options("xlabel(43(8)110, valuelabel) xtitle(chamber entry period) title(`title_`var'')") noconfid(1) xl(6) recode(0)
}

cd ".\Figures"

foreach j in 1 2 3 4 {
	local gph
	foreach i in duree_mee meein4 deskrej ferme_among_renvoi delibwopt numaudmee{
		local gph `gph' Graph_tentry_cutoff_`i'_`j'.gph
		graph combine `gph' , scheme(s2mono) ysize(1) xsize(2.3)
		
	}
	local k=`j'+5
	graph export "figureA`k'.pdf", replace
}

cd ..


* FIGURE A11 (SAME START DATE)
********************************

use "Data\SoJcases", clear //unlike for other models, do not restrict time window here (different running variable)

local title_duree_mee "A. Duration (days), size(medium)"
local title_meein4 "B. Likelihood of concluding in 4 months, size(medium)"

foreach var in duree_mee meein4{
	reg `var' ib77.tentry ib44.code_chambre2, cluster(cham2_tentry)
	mygraphP tentry, save(law_`var') options("xlabel(43(8)110, valuelabel) xtitle(chamber entry period) title(`title_`var'')") xl(2) recode(0)
}

cd ".\Figures"

local gph
foreach i in law_duree_mee law_meein4{ 
	local gph `gph' Graph_tentry_`i'.gph
}
graph combine `gph' , scheme(s2mono) ysize(1) xsize(2.3)
graph export "figureA11.pdf", replace

cd ..



* FIGURE A12 (JUDGES' WORKLOAD)
********************************

use "Data\SoJjudges", clear

local title_magnumin "A. Incoming caseload, size(medium)"
local title_magnumongoing "B. Ongoing caseload, size(medium)"
local title_magnumheard "C. Cases heard, size(medium)"

replace tsinceTa=tsinceTa+1000
foreach var in magnumin magnumongoing magnumheard{
	reg `var' ib996.tsinceTa ib1.calmth magcolleg, cluster(t)
	mygraphP tsinceTa, save(`var') options("xlabel(-40(8)20) title(`title_`var'') xtitle(hearing period relative to decree application)" ) xl(1) recode(1)
}
replace tsinceTa=tsinceTa-1000

cd ".\Figures"
local gph
foreach i in magnumin magnumongoing magnumheard{
	local gph `gph' Graph_tsinceTa_`i'.gph
}
graph combine `gph', scheme(s2mono) altshrink 
graph export "figureA12.pdf", replace

cd ..



* FIGURE A14
********************************

*Panel A
use "Data\SoJhearings", clear
drop if tsinceTa<-38 | tsinceTa>20
**time period is restricted to the same window used for main regressions
label var tsinceTa "t since decree application"

replace tsinceTa=tsinceTa+1000 
reg numin ib996.tsinceTa ib1.calmth ib44.code_chambre, cluster(t)
mygraphP tsinceTa, save(numin) options("xlabel(-40(8)20) xtitle(hearing period) title(A. Size of incoming caseload (chamber-level), size(medium))") xl(1) recode(1)
replace tsinceTa=tsinceTa-1000


*Panels B-D
use "Data\SoJcases", clear
drop if tentafterT<-38 | tentafterT>20

local title_montabm "B. Above-median claims, size(medium)"
local title_moredemordef "C. More than one party on either side, size(medium)"
local title_typecommercial "D. Commercial case, size(medium)"

replace tentafterT=tentafterT+1000
foreach var in moredemordef montabm{
	reg `var' ib996.tentafterT ib1.entcalmth ib44.code_chambre2, cluster(cham2_tentry)
	mygraphP tentafterT, save(check`var') options("xlabel(-40(8)20) xtitle(chamber entry period) title(`title_`var'')") xl(1) recode(1)
}
reg typecommercial ib996.tentafterT ib1.entcalmth , cluster(cham2_tentry)
mygraphP tentafterT, save(checktypecommercial) options("xlabel(-40(8)20) xtitle(chamber entry period) title(`title_typecommercial')") xl(1) recode(1)
replace tentafterT=tentafterT-1000

/* commented-out as istca2012 cannot be included in the replication data
*Panels E-G
use "Data\SoJfirmparties", clear
foreach outcome in istca2012{
	forval v=0/2{
		if "`v'"=="0"{
			local if if istca2012!=. //to ensure the below code works also for v=0
			local title E. Firm revenue (IHS transformation, pooled)
		}
		if "`v'"=="1"{
			local if if side1==1
			local title F. Firm revenue (IHS transformation, plaintiff)
		}
		if "`v'"=="2"{
			local if if side2==1
			local title G. Firm revenue (IHS transformation, defendant)
		}
	replace tentafterT=tentafterT+1000
	reg istca2012 ib996.tentafterT ib1.entcalmth ib44.code_chambre2 `if', cluster(cham2_tentry)
	mygraphP tentafterT,  save(checkistca2012`v') options("xlabel(-40(8)20) xtitle(chamber entry period) title(`title', size(medium))") xl(1) recode(1)
	replace tentafterT=tentafterT-1000
	}
}
*/
cd ".\Figures"

local gph
foreach i in checkmontabm checkmoredemordef checktypecommercial{
    *removed checkistca20120 checkistca20121 checkistca20122 due to the above commenting-out
	local gph `gph' Graph_tentafterT_`i'.gph
}
graph combine "Graph_tsinceTa_numin.gph" `gph', scheme(s2mono) altshrink 
graph export "figureA14.pdf", replace



********************************
* 6. REMOVE TEMP FILES
********************************

local gphlist: dir "`c(pwd)'" files "*.gph"
foreach i of local gphlist{
	erase `i'
}

cd ..
cap erase ridgeline_plot.R
cap erase Rplots.pdf


